home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3626 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: newshub.cts.com!usenet
  2. From: jfitz@vmbb.cts.com (Jim Fitzgerald)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Type conversion
  5. Date: Tue, 30 Jan 1996 06:29:49 GMT
  6. Organization: CTS Network Services
  7. Message-ID: <4ekd09$m0v@newshub.cts.com>
  8. References: <4ejjka$2rf@news3.cts.com> <9601300014.AA22125@dxmint.cern.ch>
  9. NNTP-Posting-Host: phobos.spacelink.com
  10.  
  11.  
  12. This makes perfect sense..  Thanks Dan!!
  13.  
  14. -Jim
  15.  
  16. Dan Pop <danpop@mail.cern.ch> wrote:
  17.  
  18. >jfitz@vmbb.cts.com (Jim Fitzgerald) writes:
  19.  
  20. >>  Was wondering if a guru out there could tell me why the following
  21.  
  22. >There is no need to be a guru to answer the question.  Only basic C
  23. >understanding is needed.
  24.  
  25. >>code fragment for extracting an long from a buffer does not work.
  26. >>Following the bad code, is a fragment that does work.. but is fairly
  27. >>cheezy! )..
  28. >>
  29. >>This code compiles and runs but returns INCORRECT results:
  30. >>
  31. >>char buffer[512];
  32. >>long  node_left, node_right;
  33. >>{
  34. >>  node_left  =  (long)*(buffer+4);
  35. >>  node_right=  (long)*(buffer+8);
  36. >>}
  37.  
  38. >What you say here is: "take the char stored at address buffer+4 and
  39. >convert it to long".  This is clearly not what you meant, so the correct
  40. >expression is: 
  41.  
  42. >    node_left = *(long *)(buffer+4);
  43.  
  44. >which converts buffer+4 into a pointer to long and then retrieves the
  45. >long value stored at that address (dereferences the pointer in C-speak).
  46.  
  47. >Note that this kind of code is very unsafe, because there is no guarantee
  48. >that buffer+4 is a legal address for a long.  If it isn't, the program will
  49. >crash and burn on platforms which are sensitive to data alignment issues.
  50.  
  51. >Dan
  52. >-- 
  53. >Dan Pop
  54. >CERN, CN Division
  55. >Email: danpop@mail.cern.ch 
  56. >Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  57.  
  58.  
  59.